/*
 * @Description: 表格分页
 * @Author: seadon
 * @LastEditors: seadon
 * @Date: 2021-04-29 15:48:52
 * @LastEditTime: 2021-12-27 18:35:33
 */
import { computed, unref, ref } from 'vue'
import { isBoolean } from '@/utils'
import { i18n } from '@/locales'
import { PaginationProps } from '../types/pagination'
import { CURRENT, SIZE, PAGE_SIZE, PAGE_SIZE_OPTIONS } from '../constant'
const { $t } = i18n

export default function useTablePagination(
	customPagination: Partial<PaginationProps> | boolean
) {
	const configRef = ref<PaginationProps>({})
	const show = ref(true)

	const getPaginationInfo = computed((): PaginationProps | boolean => {
		if (!unref(show) || (isBoolean(customPagination) && !customPagination)) {
			return false
		}

		return {
			current: CURRENT,
			pageSize: PAGE_SIZE,
			size: SIZE,
			defaultPageSize: PAGE_SIZE,
			pageSizeOptions: PAGE_SIZE_OPTIONS,
			showTotal: total => $t('common.showTotal', `共 ${total} 条`, { total }),
			showSizeChanger: true,
			showQuickJumper: true,
			...(isBoolean(customPagination)
				? {}
				: customPagination?.total
				? { ...customPagination, total: unref(customPagination.total) }
				: customPagination),
			...unref(configRef),
		}
	})

	function setPagination(info: Partial<PaginationProps>) {
		const paginationInfo = unref(getPaginationInfo)
		configRef.value = {
			...(!isBoolean(paginationInfo) ? paginationInfo : {}),
			...info,
		}
	}

	function getPagination() {
		return unref(getPaginationInfo)
	}

	function getShowPagination() {
		return unref(show)
	}

	async function setShowPagination(flag: boolean) {
		show.value = flag
	}

	return {
		getPagination,
		getPaginationInfo,
		setShowPagination,
		getShowPagination,
		setPagination,
	}
}
